package com.redis.demo.rabbitmq.rpc;

import com.rabbitmq.client.*;
import com.redis.demo.rabbitmq.Constants.Constants;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeoutException;

/*
* 发送请求，接收响应
*
*
* */
public class RpcClient {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost(Constants.HOST);
        factory.setPort(Constants.PORT);
        factory.setUsername(Constants.USERNAME);
        factory.setPassword(Constants.PASSWORD);
        factory.setVirtualHost(Constants.VIRTUALHOST);
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(Constants.RPC_REQUEST_QUEUE,true,false,false,null);
        channel.queueDeclare(Constants.RPC_RESPONSE_QUEUE,true,false,false,null);


        String correlationId= UUID.randomUUID().toString();
        AMQP.BasicProperties props =new AMQP.BasicProperties().builder()
                //回调
                .replyTo(Constants.RPC_RESPONSE_QUEUE)
                .correlationId(correlationId)
                .build();


        String msg="hello mq";


        channel.basicPublish("",Constants.RPC_REQUEST_QUEUE,props,msg.getBytes());
        final BlockingQueue<String> queue=new ArrayBlockingQueue<>(1);


        DefaultConsumer consumer=new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println(new String(body));
                System.out.println("接收到回调消息");
                if (correlationId.equals(properties.getCorrelationId())){
                    //如果correlationid校验成功
                    queue.offer(msg);


                }

            }
        };

        channel.basicConsume(Constants.RPC_RESPONSE_QUEUE,true,consumer);

        String take = queue.take();
        System.out.println(take);


    }
}
